/*
 * @Date: 2021-11-30 15:42:07
 * @LastEditors: 春贰
 * @Desc: 
 * @LastEditTime: 2022-10-10 16:28:25
 * @FilePath: \web\src\core\route\permission.js
 */
import store from "@/core/store"
import NProgress from "nprogress"
import router from "@/core/route/index"
import permissionRoutes from './module/main-routes'
import { toTree, hasRoute } from "@/core/tools/menu"

//根据菜单树生成路由
export const createRouteByTree = (menuList) => {

  let userRoutes = [];
  menuList.forEach((menu) => {
    let { id, type, parent, icon, name, children = [], path, title,isshowmenu } = menu
    
    //处理name 带不带斜杠都可以
    name = name.indexOf("/") === 0 ? name : "/" + name
    let tempath = path == "" ? name : path
    let currentMenu = {};
    if (type == 'dir') {
      currentMenu = {
        id, path: tempath, name, isshowmenu, parent,
        meta: { title, icon,isshowmenu },
        children: children.length === 0 ? [] : createRouteByTree(children)
      }
      if (children.length <= 0) {
        currentMenu.isshowmenu = 2
      }
      userRoutes.push(currentMenu)
    }
    if (type == 'menu') {
      currentMenu = {
        id, path: tempath, name, isshowmenu, parent,
        meta: { title, icon,isshowmenu }
      }
      userRoutes.push(currentMenu)
    }
  })
  return userRoutes;
}

//列表生成菜单
export const createRouteByList = menuList => {
  const tree = toTree(menuList)
  console.log("tree", tree);
  return createRouteByTree(tree)
}


//设置路由
export const setUserRouteComponent = routes => {
  routes.forEach(r => { 
    
      r.component = r.parent == "0" ? permissionRoutes.Layout : permissionRoutes[r.name]
      if (r.children && r.children.length > 0) {
        setUserRouteComponent(r.children)
      }
    //   if (r.isshowmenu ==1 ) {
    // } else {
    //   //执行客户端
    //   r.component = r.parent == "0" ? permissionRoutes.MesClientLayout : permissionRoutes[r.name]
    //   if (r.children && r.children.length > 0) {
    //     setUserRouteComponent(r.children)
    //   }
    // } 
  }) 
}

//设置标题
const setDocumentTitle = title => {
  document.title = `go-andv-${title}`
}
/**
 * 前置拦截
 * 
 * @param to    前往路由
 * @param from  来至路由
 * @param next  放行路由
 */
export var permissionController = async (to, from, next) => {
  NProgress.start();
  const { meta } = to
  setDocumentTitle(meta.title)
  await store.dispatch('app/execCancelToken') //取消未跳转的路由
  // 检测登录 
  if (!to.fullPath.includes('login') && !localStorage.getItem('USER_TOKEN')) {
    next({ path: '/login' })

  } else { 
    // 基本路由 是否包括 前往路由 ,不包括就去查询 更新
    if (!router.getRoutes().map(it => it.path).includes(to.path)) {
      const menus = store.getters.menu 
      //开发环境添加自动生成code
      if (process.env.NODE_ENV == "development") {
        if (!menus.map(it => it.name).includes("/autocode")) {
          menus.push(
            { icon: "", id: -1, name: "/autocode", parent: 0,  path: "", sort: 99, status: 1, isshowmenu: 1,  title: "autocode", type: "dir", },
            { icon: "", id: -2, name: "/autocode/index", parent: -1,  path: "", sort: 99, status: 1, isshowmenu: 1, title: "autocode", type: "menu", }
            )
        } 
      } 
      const userRoutes = createRouteByList(menus)
      //二次储存生成好的路由
      store.commit('app/UPDATE_ROUTES', userRoutes)

      // 动态路由 是否包括 前往路由
      if (hasRoute(userRoutes, to.path)) {
        // 设置 路由 布局
        setUserRouteComponent(userRoutes)
        userRoutes.forEach(r => {
          router.addRoute(r)
        }) 
        next(to.fullPath)
      } else {
        // 404 
        next('/error/404')
      }
    } else {
      next()
    }
  }
}
